/**
 * VUE 全局方法
 * Created by home on 2017-05-23.
 */
import axios from 'axios'
import stringify from 'qs/lib/stringify'
import { Message, Notification } from 'element-ui'

/**
 * ajax请求
 * @param url 请求地址
 * @param method 请求类型 get post put delete
 * @param data 参数
 * @param success 正常回调
 * @param error 错误回调
 */
export function request(url, method, data, success, error) {
  function success_request(res) {
    let msg = res.data.msg
    switch (parseInt(res.data.code)) {
      case 1:
        if (msg) {
          Message.success(msg)
        }
        success(res.data)

        break
      case -1:
        if (msg) {
          Message.error(msg)
        } else {
          Message.error('用户名或密码错误')
        }
        success(res.data)

        break

      default:
        success(res.data)
    }
  }
  function error_request(err) {
    let response = err.response
    if (response) {
      switch (parseInt(response.status)) {
        case 419:
          axios.get('admin/csrf')
          return axios(option)
            .then(success_request)
            .catch(error_request)
          break
        case 401:
          Message.error(response.data.msg)
          window.location.href = './#/login'
          break
        case 422:
          Message.error(response.data.msg)
          break
        case 404:
        case 405:
          Message.error('请求地址错误')
          break
        case 500:
          Message.error('服务器忙')
          break
        default:
          Message.error(response.message)
          break
      }
    }

    typeof error == 'function' && error()
  }
  let option = {
    baseURL: '/admin/',
    url: url,
    method: method,
    headers: {
      // Authorize: window.localStorage.getItem('ak')
    }
  }
  switch (method) {
    case 'get':
      option.params = data
      break
    case 'post':
      option.data = stringify(data)
      break
    default:
      option.data = data
      break
  } // 发起一个POST请求
  return axios
    .request(option)
    .then(success_request)
    .catch(error_request)
}
